package cn.tianya.irock.bll;

import java.sql.Date;
import java.text.MessageFormat;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

import cn.tianya.irock.cache.AppCache;
import cn.tianya.irock.cache.ICache;
import cn.tianya.irock.core.DateTime;
import cn.tianya.irock.core.HttpContext;
import cn.tianya.irock.core.HttpRuntime;
import cn.tianya.irock.data.dalfactory.DataAccess;
import cn.tianya.irock.data.idal.ISiteSettingsDataProvider;
import cn.tianya.irock.data.model.Action;
import cn.tianya.irock.data.model.Page;
import cn.tianya.irock.data.model.Site;
import cn.tianya.irock.data.model.SiteSettings;
import cn.tianya.irock.data.model.Template;
import cn.tianya.irock.data.model.UrlPattern;
import cn.tianya.irock.enums.DataProviderAction;
import cn.tianya.irock.enums.LogType;
import cn.tianya.irock.util.DataSet;


public class SiteManager {
	private static ISiteSettingsDataProvider provider;
	
	public static String GROUP_TEMPLATE = "GROUP_TEMPLATE";
	public static String GROUP_URL = "GROUP_URL";
	public static String GROUP_SETTING = "GROUP_SETTING";
	public static String GROUP_PAGE = "GROUP_PAGE";
	public static String GROUP_ACTION = "GROUP_ACTION";
	public static String GROUP_SITE = "GROUP_SITE";
	
	public static String KEY_TEMPLATES = "sitemanager:templates_idx:{0}_size:{1}";
    public static String KEY_TEMPLATE_INFO = "site:template_site:{0}_page:{1}_method:{2}";
    public static String KEY_TEMPLATE_CONTENT = "site:template:content_id:{0}";
    public static String KEY_TEMPLATE = "site:template_id:{0}";  
	public static String KEY_URLS = "site:urls_id:{0}_idx:{1}_size:{2}";
	public static String KEY_URL = "site:url_sid:{0}_pid:{1}_aid:{2}";
	public static String KEY_SETTING = "site:setting_id{0}";
	public static String KEY_SETTINGS = "site:settings_idx:{0}_size:{1}";
	public static String KEY_SETTING_SITE = "site:settings_site:{0}";
	public static String KEY_SITE_URL = "site:site_url:{0}";
	public static String KEY_SITE_NAME = "site:site_name:{0}";
	public static String KEY_SITE = "site:site_id:{0}";
	public static String KEY_SITES_SETTINGS = "site:sites_sid:{0}";
	public static String KEY_SITES = "site:sites_idx:{0}_size:{1}";
	public static String KEY_SITES_PAGE = "site:sites_pid:{0}";
	public static String KEY_PAGES = "site:pages_sid:{0}_idx:{1}_siez:{2}";
	public static String KEY_PAGE = "sit:page_id:{0}";
	public static String KEY_ACTION = "site:action_id:{0}";
	public static String KEY_ACTIONS = "site:actions_idx:{0}_size:{1}";
	
	static {
		provider = DataAccess.createSiteDataProvider();
	}
	
	public static int addAction(Action action) {
		int result = provider.createUpdateDeleteAction(action, DataProviderAction.Create);
		AppCache.clear(GROUP_ACTION);
		return result;
	}
	
	public static int updateAction(Action action) {
		Action old = getAction(action.getActionId());
		Logs.add(old, LogType.UpdateAction);
		int result = provider.createUpdateDeleteAction(action, DataProviderAction.Update);
		
		AppCache.clear(GROUP_ACTION);
		return result;
	}
	
	public static int deleteAction(Action action) {
		int result = provider.createUpdateDeleteAction(action, DataProviderAction.Delete);
		
		AppCache.clear(GROUP_ACTION);
		return result;
	}
		
	public static Action getAction(int actionId) {
		String key = MessageFormat.format(KEY_ACTION, actionId);
		Action page = null;
		
		page = (Action)AppCache.get(key);
		if (page == null) {
			page = provider.getAction(actionId);
			AppCache.add(key, GROUP_ACTION, page);
		}
		return page;
	}
			
	@SuppressWarnings("unchecked")
	public static DataSet<Action> getActions(int pageIndex, int pageSize) {
		String key = MessageFormat.format(KEY_ACTIONS, pageIndex, pageSize);
		DataSet<Action> methods = null;
		
		methods = (DataSet<Action>)AppCache.get(key);
		if (methods == null) {
			methods = provider.getActions(pageIndex, pageSize);
			AppCache.add(key, GROUP_ACTION, methods);
		}
		return methods;
	}
		
	public static Page getPage(int pageId) {
		String key = MessageFormat.format(KEY_PAGE, pageId);
		Page page = null;
		
		page = (Page)AppCache.get(key);
		if (page == null) {
			page = provider.getPage(pageId);
			AppCache.add(key, GROUP_PAGE, page);
		}
		return page;
	}
	
	public static DataSet<Page> getPages(int settingsId) {
		return getPages(settingsId, 1, Integer.MAX_VALUE);
	}
	
	@SuppressWarnings("unchecked")
	public static DataSet<Page> getPages(int settingsId, int pageIndex, int pageSize) {
		String key = MessageFormat.format(KEY_PAGES, settingsId, pageIndex, pageSize);
		DataSet<Page> data = null;
		
		data = (DataSet<Page>)AppCache.get(key);
		if (data == null) {
			data = provider.getPages(settingsId, pageIndex, pageSize);
			HttpRuntime.cache().add(key, GROUP_PAGE, data);
		}
		return data;
	}
	
	@SuppressWarnings("unchecked")
	public static List<Site> getPageSites(int pageId) {
		String key = MessageFormat.format(KEY_SITES_PAGE, pageId);
		List<Site> sites = null;
		
		sites = (List<Site>)HttpRuntime.cache().get(key);
		if (sites == null) {
			sites = provider.getPageSites(pageId);
			AppCache.add(key, GROUP_PAGE, sites, ICache.DAY_FACTOR);
		}
		return sites;
	}
		
	public static Map<String, Page> getPageMap(int settingsId) {
		Map<String, Page> map = null;
		List<Page> refers = null;
		
		refers = getPages(settingsId).getObjects();
		map = new Hashtable<String, Page>();
		for (Page pf:refers) {
			map.put(pf.getName(), pf);
		}
		return map;
	}
	
	public static Page addPage(int settingsId, String name, String refer) {
		Page page = new Page();
		
		page.setName(name);
		page.setRefer(refer);
		page.setUserId(Users.getUser().getUserId());
		page.setDateCreated(new Date(DateTime.now().getTime()));
		SiteManager.addPage(page);
		SiteManager.addPageToSiteSettings(page, settingsId);
		
		return page;
	}
	
	public static int addPage(Page page) {
		int result = provider.createUpdateDeletePage(page, DataProviderAction.Create);
		AppCache.clear(GROUP_PAGE);
		return result;
	}
	
	public static void addPageToSiteSettings(Page page, int settingsId) {
		provider.addPageToSiteSettings(page, settingsId);
		AppCache.clear(GROUP_PAGE);
	}
	
	public static int updatePage(Page page) {
		Page old = getPage(page.getPageId());
		Logs.add(old, LogType.UpdatePage);
		int result = provider.createUpdateDeletePage(page, DataProviderAction.Update);
		AppCache.clear(GROUP_PAGE);
		return result;
	}
	
	public static int deletePage(Page page) {
		int result = provider.createUpdateDeletePage(page, DataProviderAction.Delete);
		AppCache.clear(GROUP_PAGE);
		return result;
	}
	
	public static Site addSite(SiteSettings settings, String url, String name) {
		Site site = null;
		
		site = new Site();
		site.setUrl(url);
		site.setName(name);
		site.setDescription(name);
		site.setSettings(settings);
		
		site.setUserId(Users.getUser().getUserId());
		site.setDateCreated(new Date(DateTime.now().getTime()));
		SiteManager.addSite(site);
		return site;
	}
	
	public static int addSite(Site site) {
		int siteId = provider.createUpdateDeleteSite(site, DataProviderAction.Create);
		
		addSiteToSettings(site.getSiteId(), site.getSettings().getSiteSettingsId());
		AppCache.clear(GROUP_SITE);
		return siteId;
	}
	
	public static void updateSite(Site site) {
		Site old = getSite(site.getSiteId());
		//Logs.add(old, LogType.UpdateSite);
		provider.createUpdateDeleteSite(site, DataProviderAction.Update);
		updateSiteToSettings(site.getSiteId(), site.getSettings().getSiteSettingsId());
		AppCache.clear(GROUP_SITE);
	}
		
	public static void addSiteToSettings(int siteId, int settingsId) {
		provider.addSiteToSettings(siteId, settingsId);
		AppCache.clear(GROUP_SITE);
	}
	
	public static void updateSiteToSettings(int siteId, int settingsId) {
		provider.updateSiteSettings(siteId, settingsId);
		AppCache.clear(GROUP_SITE);
	}
		
	public static Site findSiteByname(String sitename) {
		String key = MessageFormat.format(KEY_SITE_NAME, sitename);
		Site site = null;
		
		site = (Site)AppCache.get(key);
		if (site == null) {
			site = provider.findSiteByname(sitename);
			AppCache.add(key, GROUP_SITE, site);
		}
		return site;
	}
		
	public static Site getSite(int siteId) {
		String key = MessageFormat.format(KEY_SITE, siteId);
		Site site = null;
		
		site = (Site)AppCache.get(key);
		if (site == null) {
			site = provider.getSite(siteId);
			AppCache.add(key, GROUP_SITE, site);
		}
		return site;
	}

	@SuppressWarnings("unchecked")
	public static DataSet<Site> getSites(int pageIndex, int pageSize) {
		String key = MessageFormat.format(KEY_SITES, pageIndex, pageSize);
		DataSet<Site> sites = null;
		
		sites = (DataSet<Site>)AppCache.get(key);
		if (sites == null) {
			sites = provider.getSites(pageIndex, pageSize);
			AppCache.add(key, GROUP_SITE, sites, ICache.DAY_FACTOR);
		}
		return sites;
	}
	
	public static Site getCurrentSite() {
		return getCurrentSite(HttpContext.getSiteUrl(HttpContext.current()));
	}
		
	public static Site getCurrentSite(String siteUrl) {
    	String key = MessageFormat.format(KEY_SITE_URL, siteUrl);
        Site site = (Site)AppCache.get(key) ;
        
        if (site == null) {
        	site = provider.getSite(siteUrl);
            AppCache.add(key, GROUP_SITE, site);
        }
        return site;
	}
	
	@SuppressWarnings("unchecked")
	public static List<Site> getSitesBySettings(int settingsId) {
		String key = MessageFormat.format(KEY_SITES_SETTINGS, settingsId);
		List<Site> sites = null;
		
		sites = (List<Site>)AppCache.get(key);
		if (sites == null) {
			sites = provider.getSites(settingsId);
			AppCache.add(key, GROUP_SITE, sites, ICache.DAY_FACTOR);
		}
		return sites;
	}
	
	public static int addSiteSettings(SiteSettings settings) {
		int result = provider.createUpdateDeleteSiteSettings(settings, DataProviderAction.Create);
		AppCache.clear(GROUP_SETTING);
		return result;
	}
	
	public static int updateSiteSettings(SiteSettings settings) {
		int result = provider.createUpdateDeleteSiteSettings(settings, DataProviderAction.Update);
		AppCache.clear(GROUP_SETTING);
		return result;
	}
		
	@SuppressWarnings("unchecked")
	public static DataSet<SiteSettings> getSettings(int pageIndex, int pageSize) {
		String key = MessageFormat.format(KEY_SETTINGS, pageIndex, pageSize);
		DataSet<SiteSettings> settings = (DataSet<SiteSettings>)AppCache.get(key);;
		
		if (settings == null) {
			settings = provider.getSettings(pageIndex, pageSize);
			AppCache.add(key, GROUP_SETTING, settings);
		}
		return settings;
	}
	
	public static SiteSettings getCurrentSiteSettings() {
		return getCurrentSite().getSettings();
	}
	
	public static SiteSettings getSiteSettingsBySite(int siteId) {
		String key = MessageFormat.format(KEY_SETTING_SITE, siteId);
		SiteSettings settings = (SiteSettings)AppCache.get(key);
		
		if (settings == null) {
			settings = provider.getSiteSettingsBySite(siteId);
			AppCache.add(key, GROUP_SETTING, settings);
		}
		return settings;
	}
		
	public static SiteSettings getSiteSettings(int settingsId) {
		String key = MessageFormat.format(KEY_SETTING, settingsId);
		SiteSettings settings = (SiteSettings)AppCache.get(key);
		
		if (settings == null) {
			settings = provider.getSiteSettings(settingsId);
			AppCache.add(key, GROUP_SETTING, settings);
		}
		return settings;
	}
	
	
	public static int addUrlPattern(UrlPattern url) {
		int result = provider.createUpdateDeleteUrlPattern(url, DataProviderAction.Create);
		AppCache.clear(GROUP_URL);
		return result;
	}
	
	public static int updateUrlPattern(UrlPattern url) {
		int result = provider.createUpdateDeleteUrlPattern(url, DataProviderAction.Update);
		
		AppCache.clear(GROUP_URL);
		return result;
	}
	
	public static int deleteUrlPattern(UrlPattern url) {
		int result = provider.createUpdateDeleteUrlPattern(url, DataProviderAction.Delete);
		
		AppCache.clear(GROUP_URL);
		return result;
	}
	
    public static UrlPattern getUrlPattern(int settingsId, int pageId, int actionId) {
    	String key = MessageFormat.format(KEY_URL, settingsId, pageId, actionId);
    	UrlPattern url = (UrlPattern)AppCache.get(key) ;;
    	
    	if (url == null) {
    		url = provider.getUrlPattern(settingsId, pageId, actionId);
    		AppCache.add(key, GROUP_URL, url, ICache.MONTH_FACTOR);
    	}
    	return url;
    }
    
    public static DataSet<UrlPattern> getUrlPatterns(int settingsId) {
		return getUrlPatterns(settingsId, 1, Integer.MAX_VALUE);
	}
    
    @SuppressWarnings("unchecked")
    public static DataSet<UrlPattern> getUrlPatterns(int settingsId, int pageIndex, int pageSize) {
		String key = MessageFormat.format(KEY_URLS, settingsId, pageIndex, pageSize);
		DataSet<UrlPattern> datas = (DataSet<UrlPattern>)AppCache.get(key);
		
		if (datas == null) {
			datas = provider.getUrlPatterns(settingsId, pageIndex, pageSize);
			AppCache.add(key, GROUP_URL, datas, ICache.MONTH_FACTOR);
		}
		return datas;
	}
        
    public static String getTemplateContent(int tempId) {
    	String key = MessageFormat.format(KEY_TEMPLATE_CONTENT, tempId);
    	String content = (String)AppCache.get(key);
    	
    	if (content == null) {
    		content = provider.getTemplateContent(tempId);
			AppCache.add(key, GROUP_TEMPLATE, content, ICache.DAY_FACTOR);
		}
		return content;
    }
    
	public static int addTemplate(Template tp) {
		int result = provider.createUpdateDeleteTemplate(tp, DataProviderAction.Create);
		AppCache.clear(GROUP_TEMPLATE);
		return result;
	}
	
	public static int updateTemplate(Template tp) {
		Template old = getTemplate(tp.getTemplateId());
		Logs.add(old, LogType.UpdatePageTemplate);
		int result = provider.createUpdateDeleteTemplate(tp, DataProviderAction.Update);
		
		AppCache.clear(GROUP_TEMPLATE);
		return result;
	}
	
	public static int deleteTemplate(Template tp) {
		int result = provider.createUpdateDeleteTemplate(tp, DataProviderAction.Delete);
		AppCache.clear(GROUP_TEMPLATE);
		return result;
	}
    
    public static Template getTemplate(int tempId) {
    	String key = MessageFormat.format(KEY_TEMPLATE, tempId);
    	Template template = (Template)AppCache.get(key);
    	
    	if (template == null) {
			template = provider.getTemplate(tempId);
			AppCache.add(key, GROUP_TEMPLATE, template, ICache.DAY_FACTOR);
		}
		return template;
    }
	
    
	public static Template getTemplate(Site site, String page, String method) {
		String key = MessageFormat.format(KEY_TEMPLATE_INFO, site.getName(), page, method);
		Template template = (Template)AppCache.get(key);
		
		if (template == null) {
			template = provider.getTemplate(site.getSettings().getSiteSettingsId(), page, method);
			AppCache.add(key, GROUP_TEMPLATE, template, ICache.DAY_FACTOR);
		}
		return template;
	}
	
	
	@SuppressWarnings("unchecked")
	public static DataSet<Template> getTemplates(int pageIndex, int pageSize) {
		String key = null;
		DataSet<Template> datas = null;
		
		key = MessageFormat.format(KEY_TEMPLATES, pageIndex, pageSize);
		datas = (DataSet<Template>)AppCache.get(key);
		if (datas == null) {
			datas = provider.getTemplates(pageIndex, pageSize);
			AppCache.add(key, GROUP_TEMPLATE, datas, ICache.DAY_FACTOR);
		}
		return datas;
	}
}
